/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="routeOptimize">
    <el-container>
      <el-aside width="180px">
        <PlanMenu :planData="planData"
        :zIndexObj="zIndexObj"
        :loading="loading"
        @maskChange="maskChange"
        @chooseRoute="chooseRoute"
        @resetContentComponent="resetContentComponent"
        @editStart="editStart"
        @refresh="refresh"/>
      </el-aside>
      <el-main>
        <div class="main-container" style="border: 0px solid yellow;height: 90%;">
          <el-tabs v-model="editableTabsValue" type="card"  @edit="handleTabsEdit" :before-leave="beforeLeave" style="border: 0px solid yellow;height: 100%;">
            <el-tab-pane
              :closable="true"
              :key="item.tabName"
              v-for="(item, index) in editableTabs"
              :label="$t('openatc.greenwaveoptimize.pattern') + ' ' +  item.tabName"
              :name="item.tabName"
            >
              <div class="panel-content" style="border: 0px solid yellow;height: 100%;">
                <div style="border: 0px solid red;height: 12%;">
                  <div class="route-filter-container" style="display:flex;">
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.patternName')}}：</span>
                      <el-input
                          clearable
                          size="small"
                          v-model="item.name"
                          style="width:70%;"
                          @change="onConditionChange"
                      />
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('edge.date.month')}}：</span>
                      <el-select multiple
                                  v-model="item.month"
                                  style="width:70%;"
                                  :placeholder="$t('edge.common.select')"
                                  size="small"
                                  :collapse-tags="true"
                                  @change="handleMonth(item.month, index)"
                                  @visible-change="initOldOptions(item.month, $event)">
                        <el-option
                          v-for="item in months"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('edge.date.day') }}：</span>
                      <el-select multiple
                                  style="width:70%;"
                                  v-model="item.day"
                                  :placeholder="$t('edge.common.select')"
                                  size="small"
                                  :collapse-tags="true"
                                  @change="handleDay(item.day, index)"
                                  @visible-change="initOldOptions(item.day, $event)">
                        <el-option
                          v-for="item in days"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('edge.date.date') }}：</span>
                      <el-select  multiple
                                  style="width:70%;"
                                  :collapse-tags="true"
                                  v-model="item.date"
                                  :placeholder="$t('edge.common.select')"
                                  size="small"
                                  @change="handleDate(item.date, index)"
                                  @visible-change="initOldOptions(item.date, $event)">
                        <el-option
                          v-for="item in dates"
                          :key="item"
                          :label="item"
                          :value="item">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.period')}}：</span>
                      <template>
                        <el-time-select
                          style="width:35%;"
                          size="small"
                          v-model="item.plan.start"
                          :picker-options="{
                            start: '00:00',
                            step: '00:05',
                            end: '23:59'
                          }">
                        </el-time-select>
                        <el-time-select
                          style="width:35%;"
                          size="small"
                          v-model="item.plan.end"
                          :picker-options="{
                            start: '00:00',
                            step: '00:05',
                            end: '23:59',
                            minTime: item.plan.start
                          }">
                        </el-time-select>
                      </template>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.coordinationstrategy')}}：</span>
                      <el-select v-model="item.optstrategy"
                                style="width:70%;"
                                  @change="onOptstrategyChange"
                                :placeholder="$t('openatc.common.placeholder')"
                                size="small">
                        <el-option
                          v-for="item in optstrategyOptions"
                          :key="item.value"
                          :label="$t('openatc.greenwaveoptimize.optstrategyoption' + item.id)"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.coordinationdirection')}}：</span>
                      <el-select v-model="item.direction"
                                :placeholder="$t('openatc.common.placeholder')"
                                size="small"
                                style="width:70%;"
                                @change="onDirectionChange">
                        <el-option
                          v-for="dir in directionOptions"
                          :key="dir.value"
                          :label="$t('openatc.greenwaveoptimize.directionOption' + dir.id)"
                          :disabled="item.optstrategy != 'green' && dir.value === 'all'"
                          :value="dir.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.keyintersection')}}：</span>
                      <el-select v-model="item.keyintsid"
                                :placeholder="$t('openatc.common.placeholder')"
                                style="width:70%;"
                                size="small">
                        <el-option
                          v-for="item in keyintsidOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.upspeed')}}：</span>
                      <el-input-number :controls="false"
                                      style="width:70%;"
                                      :min="0"
                                        size="small"
                                        @change="onUpspeedChange"
                                      v-model="item.upspeed"
                                      ></el-input-number>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.downspeed')}}：</span>
                      <el-input-number :controls="false"
                                      style="width:70%;"
                                      :min="0"
                                        size="small"
                                        @change="onDownspeedChange"
                                      v-model="item.downspeed"
                                      ></el-input-number>
                    </div>
                  </div>
                </div>
                <div style="height: 88%;border: 0px solid green;" class="table-container">
                  <PatternTable ref="patterntable"
                                :optList="item.devs"
                                @onNewPatternListChange="onNewPatternListChange"/>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane key="add" name="add" :closable="false">
              <span slot="label" style="padding: 8px;font-size:20px;font-weight:bold;">
                  +
              </span>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div style="display:flex;justify-content:center;">
          <el-button type="primary"  @click="onChartClick" plain>{{$t('openatc.greenwaveoptimize.spaceGraph')}}</el-button>
          <el-button type="primary"  @click="onGenerateClick" plain>{{$t('openatc.greenwaveoptimize.generate')}}</el-button>
          <!-- <el-button type="primary"  @click="onDownSendClick" plain>{{$t('openatc.greenwaveoptimize.downSend')}}</el-button> -->
          <el-button type="primary"  @click="onSaveClick" plain>{{$t('openatc.common.save')}}</el-button>
          <el-button type="primary"  @click="onExecuteClick" plain>{{$t('openatc.dutyroute.executen')}}</el-button>
          <el-button type="primary"  @click="onDownloadClick" plain>{{$t('openatc.button.download')}}</el-button>
        </div>
      </el-main>
    </el-container>
    <PlanContent v-show="false"
        :schemeData="schemeData"
        :step="step"
        :zIndexObj="zIndexObj"
        ref="planContent"
        @handlePlanChart="handlePlanChart"
        @handlePatternTable="handlePatternTable"
        @ErrorOcurrred='onErrorOcurrred'
        @resetContentComponent="resetContentComponent"/>
    <chartDialog ref="chartDialog" ></chartDialog>
    <PlanExecute ref="planExecute" ></PlanExecute>
  </div>
</template>

<script>
import PlanMenu from './planMenu'
import PlanContent from './planContent'
import { GetAllRoute } from '../../api/route'
import chartDialog from './pattern/planChart/chartDialog'
import { getMessageByCode } from '../../utils/responseMessage'
import PatternTable from './pattern/patternTable'
import dateObj from './utils.js'
import routeChart from './pattern/planChart/index'
import PlanExecute from './components/planExecute'
const { monthsModel, daysModelCh, daysModelEn, datesModel, monthsModelEn, datesModelEn } = dateObj
export default {
  name: 'GreenWaveOptimize',
  components: {
    routeChart,
    PatternTable,
    PlanMenu,
    PlanContent,
    chartDialog,
    PlanExecute
  },
  data () {
    return {
      chartData: {},
      months: monthsModel,
      days: [],
      dates: datesModel,
      planData: [],
      schemeData: [],
      step: false, // 控制第二个蒙层是否可以显示
      zIndexObj: {
        // 由于“新增”“编辑”均有蒙层，因此需动态改变可点击按钮层级
        addZIndex: 98,
        editZIndex: 98
      },
      reset: false,
      activeName: 'first',
      chooseId: 0, // 选中的计划id
      loading: false,
      keyintsidOptions: [],
      directionOptions: [{
        value: 'up',
        label: this.$t('openatc.greenwaveoptimize.directionOption1'),
        id: '1'
      }, {
        value: 'down',
        label: this.$t('openatc.greenwaveoptimize.directionOption2'),
        id: '2'
      }, {
        value: 'all',
        label: this.$t('openatc.greenwaveoptimize.directionOption3'),
        id: '3'
      }],
      optstrategyOptions: [{
        value: 'green',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption1'),
        id: '1'
      }, {
        value: 'red',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption2'),
        id: '2'
      }, {
        value: 'motorcade-end',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption3'),
        id: '3'
      }, {
        value: 'dynamicGreen',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption4'),
        id: '4'
      }],
      editableTabsValue: '1',
      routePattern: {
        'id': 1,
        'optPatternList': []
      },
      defaultOptPattern: {
        'tabName': '1',
        'month': [],
        patternid: 1,
        'day': [],
        'date': [],
        'plan': {
          'start': '11:00',
          'end': '13:00'
        },
        'optstrategy': 'green',
        'direction': 'up',
        'keyintsid': '',
        'upspeed': 0,
        'downspeed': 0,
        'devs': []
      },
      currentIndex: 0,
      editableTabs: [{
        title: '方案 1',
        tabName: '1',
        content: 'Tab 1 content',
        patternid: 1,
        'month': [],
        'day': [],
        'date': [],
        'plan': {
          'start': '11:00',
          'end': '13:00'
        },
        'optstrategy': 'green',
        'direction': 'up',
        'keyintsid': '',
        'upspeed': 0,
        'downspeed': 0,
        'devs': []
      }],
      tabIndex: 1
    }
  },
  created () {
    this.resetTab()
    let lan = this.$i18n.locale
    if (lan === 'en') {
      this.days = daysModelEn
      this.dates = datesModelEn
      this.months = monthsModelEn
    }
    if (lan === 'zh') {
      this.days = daysModelCh
      this.dates = datesModel
      this.months = monthsModel
    }
  },
  mounted () {
    this.getAllPlan()
  },
  methods: {
    handlePlanChart (routeData, patternList, greenwave) {
      let chartData = {
        routeData,
        patternList,
        greenwave
      }
      this.chartData = chartData
    },
    handlePatternTable (routeData, patternList, phaseList) {
      let index = this.currentIndex
      let patterntable = this.$refs.patterntable[index]
      patterntable.onPatternTable(routeData, patternList, phaseList)
    },
    onNewPatternListChange (newPatternList) {
      let list = JSON.parse(JSON.stringify(newPatternList))
      let editableTab = this.editableTabs[this.currentIndex]
      let devs = editableTab.devs
      let devList = []
      for (let dev of devs) {
        for (let pattern of list) {
          if (dev.agentid === pattern.agentid) {
            dev = {...dev, ...pattern}
            dev.isused = pattern.isused
            let allPatterns = pattern.allPatterns
            for (let p of allPatterns) {
              if (p.id === dev.patternid) {
                p.cycle = dev.cycle
                p.offset = dev.offset
                p.rings = dev.rings
              }
            }
            dev.patternList = JSON.parse(JSON.stringify(allPatterns))
            if (dev.feature && dev.feature.patternList) {
              dev.feature.patternList = JSON.parse(JSON.stringify(allPatterns))
            } else {
              let feature = {
                patternList: JSON.parse(JSON.stringify(allPatterns))
              }
              dev.feature = feature
            }
            devList.push(dev)
          }
        }
      }
      editableTab.devs = devList
      // this.refreshChart()
    },
    afterEnter () {
      if (this.chooseId === 0) {
        return false
      }
      let {routeData, patternList, greenwave} = {...this.chartData}
      this.$refs.routeChart.onPlanChart(routeData, patternList, greenwave)
    },
    onChartClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkData([routeData], false)
      if (!check) {
        return false
      }
      this.$refs.chartDialog.show(true, this.chartData, this.route.name)
    },
    onGenerateClick () {
      let routeData = this.editableTabs[this.currentIndex]
      // check
      let check = this.checkData([routeData], false)
      if (!check) {
        return false
      }
      let planContent = this.$refs.planContent
      planContent.handleCreate(routeData)
    },
    checkData (tabs, isCheckName = true) {
      let res = true
      if (this.chooseId === 0) {
        this.$message.warning(this.$t('openatc.greenwaveoptimize.chooseRoute'))
        return false
      }
      for (let tab of this.editableTabs) {
        if (!tab.optstrategy) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseChoseOptstrategy'))
          return false
        }
        if (isCheckName && !tab.name) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseInputPatternName'))
          return false
        }
        let filterList = this.editableTabs.filter(item => item.name === tab.name)
        if (filterList.length > 1) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.repeatPatternName'))
          return false
        }
        if (!tab.keyintsid) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseChoseKeyintersection'))
          return false
        }
        if (!tab.upspeed) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseInputUpspeed'))
          return false
        }
        if (!tab.downspeed) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseInputDownspeed'))
          return false
        }
        if (!tab.devs || tab.devs.length === 0) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.abnormalIntersections'))
          return false
        }
        // reset date
        this.resetDate(tab)
      }
      return res
    },
    onSaveClick () {
      // check
      let check = this.checkData(this.editableTabs)
      if (!check) {
        return false
      }
      let routeData = this.editableTabs
      let planContent = this.$refs.planContent
      planContent.handleSave(this.route.id, routeData)
    },
    onDownSendClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkData([routeData])
      if (!check) {
        return false
      }
      this.resetDate(routeData)
      let planContent = this.$refs.planContent
      planContent.handleDownload(this.route.id, routeData)
    },
    onExecuteClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkData([routeData])
      if (!check) {
        return false
      }
      this.resetDate(routeData)
      let planContent = this.$refs.planExecute
      planContent.onExecuteClick(this.route.id, routeData)
    },
    onDownloadClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkData([routeData])
      if (!check) {
        return false
      }
      this.resetDate(routeData)
      let planContent = this.$refs.planExecute
      planContent.onDownloadClick(this.route.id, routeData)
    },
    async onDeleteClick (targetName) {
      let routeData = this.editableTabs[this.currentIndex]
      // check
      let id = routeData.id
      if (targetName !== routeData.tabName) {
        this.$message.warning(this.$t('openatc.greenwaveoptimize.choosePattern'))
        return false
      }
      if (this.editableTabs.length === 1) {
        this.$message.warning(this.$t('openatc.greenwaveoptimize.atleastOnePattern'))
        return false
      }
      let optPatternList = this.route.optPatternList
      if (!optPatternList) {
        return true
      }
      let list = optPatternList.filter(item => item.id === id)
      if (list.length === 0) {
        return true
      } else {
        let planContent = this.$refs.planContent
        let param = {
          routeid: this.route.id,
          optpatternid: id
        }
        let flag = await planContent.handleDelete(param)
        return flag
      }
    },
    resetDate (tab) {
      let date = tab.date
      let day = tab.day
      let month = tab.month
      if (date && date.includes('全选')) {
        let index = date.indexOf('全选')
        date.splice(index, 1) // 排除全选选项
      } else if (date && date.includes('All')) {
        let index = date.indexOf('All')
        date.splice(index, 1) // 排除全选选项
      }
      if (day && day.includes(8)) {
        let index = day.indexOf(8)
        day.splice(index, 1) // 排除全选选项
      }
      if (month && month.includes(0)) {
        let index = month.indexOf(0)
        month.splice(index, 1) // 排除全选选项
      }
    },
    onConditionChange () {},
    onOptstrategyChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.optstrategy = val
      }
    },
    onDirectionChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.direction = val
      }
    },
    onUpspeedChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.upspeed = val
      }
    },
    onDownspeedChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.downspeed = val
      }
    },
    handleMonth (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.months) {
        allValues.push(item.value)
      }
      // 若是全部选择
      if (val.includes(0)) this.editableTabs[index].month = allValues
      // 取消全部选中，上次有，当前没有，表示取消全选
      if (this.oldOptions.includes(0) && !val.includes(0)) this.editableTabs[index].month = []
      // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
      // 新老数据都有全部选中
      if (this.oldOptions.includes(0) && val.includes(0)) {
        let tempIndex = val.indexOf(0)
        val.splice(tempIndex, 1) // 排除全选选项
        this.editableTabs[index].month = val
      }
      // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
      if (!this.oldOptions.includes(0) && !val.includes(0)) {
        if (val.length === allValues.length - 1) this.editableTabs[index].month = [0].concat(val)
      }
      this.oldOptions = this.editableTabs[index].month
    },
    handleDate (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.dates) {
        allValues.push(item)
      }
      // 判断中英文
      if (this.$i18n.locale === 'en') {
        // 若是全部选择
        if (val.includes('All')) this.editableTabs[index].date = allValues
        // 取消全部选中，上次有，当前没有，表示取消全选
        if (this.oldOptions.includes('All') && !val.includes('All')) this.editableTabs[index].date = []
        // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
        // 新老数据都有全部选中
        if (this.oldOptions.includes('All') && val.includes('All')) {
          let tempIndex = val.indexOf('All')
          val.splice(tempIndex, 1) // 排除全选选项
          this.editableTabs[index].date = val
        }
        // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
        if (!this.oldOptions.includes('All') && !val.includes('All')) {
          if (val.length === allValues.length - 1) this.editableTabs[index].date = ['All'].concat(val)
        }
      } else if (this.$i18n.locale === 'zh') {
        // 若是全部选择
        if (val.includes('全选')) this.editableTabs[index].date = allValues
        // 取消全部选中，上次有，当前没有，表示取消全选
        if (this.oldOptions.includes('全选') && !val.includes('全选')) this.editableTabs[index].date = []
        // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
        // 新老数据都有全部选中
        if (this.oldOptions.includes('全选') && val.includes('全选')) {
          let tempIndex = val.indexOf('全选')
          val.splice(tempIndex, 1) // 排除全选选项
          this.editableTabs[index].date = val
        }
        // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
        if (!this.oldOptions.includes('全选') && !val.includes('全选')) {
          if (val.length === allValues.length - 1) this.editableTabs[index].date = ['全选'].concat(val)
        }
      }
      this.oldOptions = this.editableTabs[index].date
    },
    handleDateInit (val, status) {
      if (status) {
        this.oldOptions = val
      } else {
        this.oldOptions = []
      }
    },
    handleDay (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.days) {
        allValues.push(item.value)
      }
      // 若是全部选择
      if (val.includes(8)) this.editableTabs[index].day = allValues
      // 取消全部选中，上次有，当前没有，表示取消全选
      if (this.oldOptions.includes(8) && !val.includes(8)) this.editableTabs[index].day = []
      // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
      // 新老数据都有全部选中
      if (this.oldOptions.includes(8) && val.includes(8)) {
        let tempIndex = val.indexOf(8)
        val.splice(tempIndex, 1) // 排除全选选项
        this.editableTabs[index].day = val
      }
      // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
      if (!this.oldOptions.includes(8) && !val.includes(8)) {
        if (val.length === allValues.length - 1) this.editableTabs[index].day = [8].concat(val)
      }
      this.oldOptions = this.editableTabs[index].day
    },
    initOldOptions (val, status) {
      if (status) {
        this.oldOptions = val
      } else {
        this.oldOptions = []
      }
    },
    beforeLeave (currentName, oldName) {
      // var self = this // 重点，如果name是add，则什么都不触发
      if (currentName === 'add') {
        if (this.chooseId === 0) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.chooseRoute'))
          return false
        }
        if (!this.route || !this.route.id) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.routeDeviceNotOnline'))
          return false
        }
        this.addTab()
        return false
      }
      for (let i = 0; i < this.editableTabs.length; i++) {
        let tab = this.editableTabs[i]
        if (tab.tabName === currentName) {
          this.currentIndex = i
          break
        }
      }
      this.initPatternList(this.chooseId)
    },
    addTab () {
      this.handleTabsEdit('', 'add')
    },
    async handleTabsEdit (targetName, action) {
      if (action === 'add') {
        let newTabName = ++this.tabIndex + ''
        let tabObj = {
          id: this.currentIndex + 1,
          name: '',
          title: this.$t('openatc.greenwaveoptimize.pattern') + ' ' + newTabName,
          tabName: newTabName,
          content: 'New Tab content',
          patternid: 1,
          'month': [],
          'day': [],
          'date': [],
          'plan': {
            'start': '08:00',
            'end': '09:30'
          },
          'optstrategy': 'green',
          'direction': 'up',
          'keyintsid': '',
          'upspeed': 0,
          'downspeed': 0,
          'devs': []
        }
        this.editableTabs.push(tabObj)
      }
      if (action === 'remove') {
        let flag = await this.onDeleteClick(targetName)
        if (!flag) {
          return false
        }
        let tabs = this.editableTabs
        let activeName = this.editableTabsValue
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.tabName === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.tabName
              }
            }
          })
        }
        this.editableTabsValue = activeName
        this.editableTabs = tabs.filter(tab => tab.tabName !== targetName)
      }
    },
    refresh () {
      this.getAllPlan()
      let planContent = this.$refs.planContent
      if (planContent) {
        planContent.closeInterval()
        planContent.startInterval()
      }
    },
    editStart () {
      let planContent = this.$refs.planContent
      if (planContent && planContent.timer > 0) {
        planContent.closeInterval()
      }
    },
    maskChange (val) {
      // 控制两个蒙层下按钮的层级关系，并判断第二个蒙层显示的时机
      if (val) {
        this.step = false
        this.zIndexObj = {
          addZIndex: 99,
          editZIndex: 96
        }
      } else {
        this.step = true
        this.zIndexObj = {
          addZIndex: 96,
          editZIndex: 99
        }
      }
    },
    resetContentComponent () {
      // 每次切换侧边栏方案时，重置销毁planContent组件
      this.reset = false
      this.$nextTick(() => {
        this.reset = true
      })
    },
    getAllPlan () {
      this.loading = true
      GetAllRoute().then(res => {
        this.loading = false
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.planData = res.data.data
      })
    },
    resetTab () {
      this.editableTabs = [
        {
          title: this.$t('openatc.greenwaveoptimize.pattern') + ' 1',
          id: 1,
          name: '',
          tabName: '1',
          content: 'Tab 1 content',
          patternid: 1,
          'month': [],
          'day': [],
          'date': [],
          'plan': {
            'start': '08:00',
            'end': '09:30'
          },
          'optstrategy': 'green',
          'direction': 'up',
          'keyintsid': '',
          'upspeed': 0,
          'downspeed': 0,
          'devs': []
        }
      ]
      this.tabIndex = 1
      this.currentIndex = 0
      this.editableTabsValue = '1'
      this.keyintsidOptions = []
      this.chartData = {}
      this.route = {}
    },
    chooseRoute (id, route) {
      // reset data
      if (id === this.chooseId) {
        return false
      }
      this.resetTab()
      this.chooseId = id
      this.route = route
      let optPatternList = route.optPatternList
      if (optPatternList && optPatternList.length > 0) {
        this.editableTabs = JSON.parse(JSON.stringify(optPatternList))
      } else {
        this.editableTabs[0].devs = route.devs
      }
      this.tabIndex = this.editableTabs.length
      this.keyintsidOptions = route.devs.map(item => {
        return {
          label: item.name,
          value: item.agentid
        }
      })
      this.initPatternList(id)
    },
    initPatternList (id) {
      let index = this.currentIndex
      let editableTab = this.editableTabs[index]
      let planContent = this.$refs.planContent
      if (planContent) {
        if (editableTab.devs.length === 0) {
          let route = JSON.parse(JSON.stringify(this.route))
          editableTab = {...editableTab, ...route}
          editableTab.id = this.currentIndex + 1
        }
        if (this.editableTabs[index].devs.length === 0) {
          this.editableTabs[index] = editableTab
        }
        planContent.init(this.chooseId, editableTab)
      }
    },
    onErrorOcurrred () {
      this.resetTab()
      let patterntable = this.$refs.patterntable
      if (patterntable instanceof Array) {
        patterntable = patterntable[0]
      }
      patterntable.newPatternList = []
    }
  }
}
</script>

<style lang="scss">
</style>
